package com.zb.jnlxc.viewResolver;

import java.io.IOException;
import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zb.jnlxc.constants.JsonConst;

public class MappingGsonConverter extends AbstractHttpMessageConverter<Object> {

    Logger RESULTLOGGER = LoggerFactory
            .getLogger(MappingGsonConverter.class);

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    /**
     * Construct a new {@code BindingJacksonHttpMessageConverter}.
     */
    public MappingGsonConverter() {
        super(new MediaType("application", "json", DEFAULT_CHARSET));
    }

    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return (canRead(mediaType));
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return (canWrite(mediaType));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        throw new UnsupportedOperationException();
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
    throws IOException,
                                                                                HttpMessageNotReadableException {
        return null;
    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage)
                                                                                throws IOException,
                                                                                HttpMessageNotWritableException {

        String jsonResponse = JSONObject.toJSONString(object, JsonConst.defaultConfig,
            SerializerFeature.DisableCircularReferenceDetect);
        if(jsonResponse.length()<=1000){
            RESULTLOGGER.debug("【结果】response={}", jsonResponse);
        }else {
            RESULTLOGGER.debug("【结果】response={}", jsonResponse.substring(0,1000)+"......");
        }
        outputMessage.getBody().write(jsonResponse.getBytes("utf-8"));
    }
}
